package com.basker.pisces.tools.web;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.basker.pisces.service.annotation.IgnoreLoginContext;
import com.basker.pisces.service.dto.DefaultServiceResult;
import com.basker.pisces.service.dto.ServiceResultFactory;
import com.basker.pisces.utils.ClassUtils;
import com.basker.pisces.utils.ReflectionUtils;

@RestController
@RequestMapping("/t/json")
public class JSONTemplateController {

    @PostMapping("/template")
    @IgnoreLoginContext
    public DefaultServiceResult<JSONObject> template(@RequestBody String typeName) {
        Class<?> type = ClassUtils.getClass(typeName.trim(), false);
        if (type == null) {
            return ServiceResultFactory.error("typeName:'" + typeName + "' is not found.");
        }

        Object instance = ReflectionUtils.createNewInstance(type);
        String jsonString = JSONObject.toJSONString(instance, SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteMapNullValue);

        return ServiceResultFactory.ok(JSON.parseObject(jsonString));
    }
}
